package org.example.curriculum_design_6_16.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.curriculum_design_6_16.entity.pojo.PaperScoringRule;
import org.example.curriculum_design_6_16.entity.pojo.ResearchPaper;
import org.example.curriculum_design_6_16.entity.pojo.Student;
import org.example.curriculum_design_6_16.entity.vo.ResearchPaperVo;
import org.example.curriculum_design_6_16.entity.vo.Result;
import org.example.curriculum_design_6_16.mapper.PaperScoringRuleMapper;
import org.example.curriculum_design_6_16.mapper.StudentMapper;
import org.example.curriculum_design_6_16.service.ResearchPaperService;
import org.example.curriculum_design_6_16.mapper.ResearchPaperMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
* @author 郑凯
* @description 针对表【research_paper(学术论文记录表)】的数据库操作Service实现
* @createDate 2025-06-23 09:55:21
*/
@Service
public class ResearchPaperServiceImpl extends ServiceImpl<ResearchPaperMapper, ResearchPaper>
    implements ResearchPaperService{
    @Autowired
    private ResearchPaperMapper researchPaperMapper;
    @Autowired
    private PaperScoringRuleMapper paperScoringRuleMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public int addResearchPaper(ResearchPaper paper) {
        // 设置默认状态为已通过
        if (paper.getReviewStatus() == null) {
            paper.setReviewStatus("APPROVED");
        }
        if (paper.getReviewComment() == null) {
            paper.setReviewComment("自动通过");
        }
        calculateScore(paper);
        return researchPaperMapper.insertResearchPaper(paper);
    }

    @Override
    public int updateResearchPaper(ResearchPaper paper) {
        // 设置默认状态为已通过
        if (paper.getReviewStatus() == null) {
            paper.setReviewStatus("APPROVED");
        }
        if (paper.getReviewComment() == null) {
            paper.setReviewComment("自动通过");
        }
        calculateScore(paper);
        return researchPaperMapper.updateResearchPaper(paper);
    }

    @Override
    public int deleteResearchPaper(Integer id) {
        return researchPaperMapper.deleteResearchPaperById(id);
    }

    @Override
    public ResearchPaperVo getResearchPaperById(Integer id) {
        ResearchPaper paper = researchPaperMapper.getResearchPaperById(id);
        if (paper == null) throw new RuntimeException("未找到论文记录");
        return convertToVo(paper);
    }

    @Override
    public List<ResearchPaperVo> getResearchPapersByStudentId(String studentId) {
        List<ResearchPaper> papers = researchPaperMapper.getResearchPapersByStudentId(studentId);
        List<ResearchPaperVo> paperVos = new ArrayList<>();
        
        for (ResearchPaper paper : papers) {
            paperVos.add(convertToVo(paper));
        }
        
        return paperVos;
    }

    @Override
    public List<ResearchPaperVo> getAllResearchPapers() {
        List<ResearchPaper> papers = researchPaperMapper.getAllResearchPapers();
        List<ResearchPaperVo> paperVos = new ArrayList<>();
        
        for (ResearchPaper paper : papers) {
            paperVos.add(convertToVo(paper));
        }
        
        return paperVos;
    }

    @Override
    public int approveResearchPaper(Integer id, String comment) {
        return researchPaperMapper.updateReviewStatus(id, "APPROVED", comment);
    }

    @Override
    public int rejectResearchPaper(Integer id, String comment) {
        return researchPaperMapper.updateReviewStatus(id, "REJECTED", comment);
    }

    @Override
    public double getTotalPaperScore(String studentId) {
        Student student = studentMapper.selectById(studentId);
        if (student == null) throw new RuntimeException("未找到该学生");
        return sumPaperScores(studentId);
    }

    @Override
    public double getTotalPaperScore(String studentId, String academicYear) {
        Student student = studentMapper.selectById(studentId);
        if (student == null) throw new RuntimeException("未找到该学生");
        return sumPaperScoresByYear(studentId, academicYear);
    }

    /**
     * 将ResearchPaper转换为ResearchPaperVo
     * @param paper 论文记录
     * @return 论文记录VO
     */
    private ResearchPaperVo convertToVo(ResearchPaper paper) {
        ResearchPaperVo vo = new ResearchPaperVo();
        vo.setId(paper.getId());
        vo.setStudentId(paper.getStudentId());
        vo.setPaperTitle(paper.getPaperTitle());
        vo.setPublication(paper.getPublication());
        vo.setPublishDate(paper.getPublishDate());
        vo.setPaperType((String) paper.getPaperType());
        vo.setStatus((String) paper.getStatus());
        vo.setContributionRank(paper.getContributionRank());
        vo.setAuthorsCount(paper.getAuthorsCount());
        vo.setScore(paper.getScore());
        vo.setProofUrl(paper.getProofUrl());
        vo.setReviewStatus((String) paper.getReviewStatus());
        vo.setReviewComment(paper.getReviewComment());
        vo.setAcademicYear(paper.getAcademicYear());
        vo.setCreatedAt(paper.getCreatedAt());
        vo.setUpdatedAt(paper.getUpdatedAt());
        
        // 查询论文类型描述
        if (paper.getPaperType() != null) {
            PaperScoringRule rule = paperScoringRuleMapper.getPaperScoringRuleByType((String) paper.getPaperType());
            if (rule != null) {
                vo.setPaperTypeDescription(rule.getDescription());
            }
        }
        
        return vo;
    }

    private void calculateScore(ResearchPaper paper) {
        // 1. 获取评分规则
        PaperScoringRule rule = paperScoringRuleMapper.getPaperScoringRuleByType((String) paper.getPaperType());
        if (rule == null) {
            paper.setScore(0.0);
            return;
        }

        // 2. 获取学生信息判断是否研三
        Student student = studentMapper.selectStudentById(paper.getStudentId());
        boolean isSenior = student != null && student.getGrade() == 3;

        // 3. 计算基础分
        Double score = rule.getBaseScore();

        // 4. 研三学生加分
        if (isSenior && (paper.getPaperType().equals("CCF_A") ||
                paper.getPaperType().equals("CCF_B") ||
                paper.getPaperType().equals("CCF_C") ||
                paper.getPaperType().equals("CCF_CONF"))) {
            score *= rule.getSeniorMultiplier();
        }

        // 5. 作者贡献度调整 (第一作者得全分，其他作者按比例)
        if (paper.getContributionRank() > 1) {
            score *= (1.0f / paper.getAuthorsCount());
        }

        paper.setScore(score);
    }

    /**
     * 计算学生论文总分
     * @param studentId 学生ID
     * @return 论文总分
     */
    private Double sumPaperScores(String studentId) {
        // 1. 获取学生的所有论文记录
        List<ResearchPaper> papers = researchPaperMapper.getResearchPapersByStudentId(studentId);

        // 2. 获取学生信息判断是否研三
        Student student = studentMapper.selectById(studentId);
        boolean isSenior3 = student != null && student.getGrade() == 3;
        double totalScore = 0.0;

        // 3. 遍历每篇论文计算得分
        for (ResearchPaper paper : papers) {
            // 只计算已审核通过的论文
            if (!"APPROVED".equals(paper.getReviewStatus())) {
                continue;
            }

            // 获取评分规则
            PaperScoringRule rule = paperScoringRuleMapper.getPaperScoringRuleByType((String) paper.getPaperType());
            if (rule == null) {
                continue;
            }

            // 计算单篇论文得分
            double paperScore = rule.getBaseScore();

            // 研三学生特殊加分规则
            if (isSenior3) {
                // 只有CCF_A/B/C/CONF类论文才乘以150%
                if (paper.getPaperType().equals("CCF_A") ||
                        paper.getPaperType().equals("CCF_B") ||
                        paper.getPaperType().equals("CCF_C") ||
                        paper.getPaperType().equals("CCF_CONF")) {
                    paperScore *= rule.getSeniorMultiplier(); // 1.5
                }
                // CORE_JOURNAL和GENERAL类型保持原分
            }

            // 作者贡献度调整 (第一作者得全分，其他作者按比例)
            if (paper.getContributionRank() > 1) {
                paperScore *= (1.0 / paper.getAuthorsCount());
            }

            // 累加到总分
            totalScore += paperScore;
        }

        return totalScore;
    }

    /**
     * 计算学生论文总分（按学年）
     * @param studentId 学生ID
     * @param academicYear 学年
     * @return 论文总分
     */
    private Double sumPaperScoresByYear(String studentId, String academicYear) {
        // 1. 获取学生在指定学年的所有论文记录
        List<ResearchPaper> papers = researchPaperMapper.getResearchPapersByStudentIdAndYear(studentId, academicYear);

        // 2. 获取学生信息判断是否研三
        Student student = studentMapper.selectById(studentId);
        boolean isSenior3 = student != null && student.getGrade() == 3;
        double totalScore = 0.0;

        // 3. 遍历每篇论文计算得分
        for (ResearchPaper paper : papers) {
            // 只计算已审核通过的论文
            if (!"APPROVED".equals(paper.getReviewStatus())) {
                continue;
            }

            // 获取评分规则
            PaperScoringRule rule = paperScoringRuleMapper.getPaperScoringRuleByType((String) paper.getPaperType());
            if (rule == null) {
                continue;
            }

            // 计算单篇论文得分
            double paperScore = rule.getBaseScore();

            // 研三学生特殊加分规则
            if (isSenior3) {
                // 只有CCF_A/B/C/CONF类论文才乘以150%
                if (paper.getPaperType().equals("CCF_A") ||
                        paper.getPaperType().equals("CCF_B") ||
                        paper.getPaperType().equals("CCF_C") ||
                        paper.getPaperType().equals("CCF_CONF")) {
                    paperScore *= rule.getSeniorMultiplier(); // 1.5
                }
                // CORE_JOURNAL和GENERAL类型保持原分
            }

            // 作者贡献度调整 (第一作者得全分，其他作者按比例)
            if (paper.getContributionRank() > 1) {
                paperScore *= (1.0 / paper.getAuthorsCount());
            }

            // 累加到总分
            totalScore += paperScore;
        }

        return totalScore;
    }
}




